package com.education.ai.service;

import com.education.ai.entity.Exercise;
import com.education.ai.entity.TeachingPlan;
import com.education.ai.service.TeachingPlanService;
import com.education.ai.util.TeacherContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.beans.factory.annotation.Qualifier;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class AiTeachingService {
    
    @Autowired
    @Qualifier("qwenWebClient")
    private WebClient qwenWebClient;
    
    @Autowired
    private ObjectMapper objectMapper;
    
    @Value("${teaching.assistant.default-model:qwen-max}")
    private String model;
    
    @Autowired
    private ExerciseService exerciseService;
    
    @Autowired
    private TeachingPlanService teachingPlanService;
    
    public TeachingPlan generateTeachingPlan(String subject, String grade, String topic) {
        String content;
        
        try {
            String prompt = String.format(
                "请为%s年级的%s课程生成一个关于\"%s\"的教学设计。要求：\n" +
                "1. 教学目标：明确具体，包含认知目标、能力目标和情感目标\n" +
                "2. 教学重难点：指出本节课的关键知识点和学生易混淆的内容\n" +
                "3. 教学准备：所需教具、多媒体资源和预习材料\n" +
                "4. 教学过程：详细的教学步骤，包括：\n" +
                "   - 课前导入（5分钟）：创设情境，激发兴趣\n" +
                "   - 新课讲解（15分钟）：主要知识点讲解\n" +
                "   - 互动环节一（5分钟）：第一个互动活动，提高学生参与度\n" +
                "   - 知识巩固（10分钟）：习题练习或应用\n" +
                "   - 互动环节二（5分钟）：第二个不同类型的互动活动\n" +
                "   - 拓展延伸（5分钟）：知识拓展或实际应用\n" +
                "   - 互动环节三（5分钟）：第三个创新性的互动活动\n" +
                "   - 总结反思（5分钟）：师生共同总结\n" +
                "5. 课后作业设计：包含基础题和拓展题\n" +
                "6. 教学评价：评价学生学习效果的方法\n\n" +
                "互动环节要求：\n" +
                "- 互动环节一：小组讨论或合作学习活动，促进学生之间的交流\n" +
                "- 互动环节二：游戏化教学设计，通过游戏或竞赛形式巩固知识\n" +
                "- 互动环节三：动手实践或创新思维活动，培养学生的实践和创新能力\n\n" +
                "请确保教学设计符合现代教育理念，注重学生主体性，能在45分钟内完成",
                grade, subject, topic);
            
            // 创建输入对象 - 直接使用prompt而非messages
            Map<String, Object> input = new HashMap<>();
            input.put("prompt", prompt);
            
            // 创建参数对象
            Map<String, Object> parameters = new HashMap<>();
            parameters.put("temperature", 0.7);
            parameters.put("max_tokens", 2000);
            parameters.put("top_p", 0.8);
            parameters.put("result_format", "text");
            
            // 创建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", model);  // 使用配置的模型名称
            requestBody.put("input", input);
            requestBody.put("parameters", parameters);
            
            System.out.println("发送请求到千问API: " + objectMapper.writeValueAsString(requestBody));
            
            String responseJson = qwenWebClient.post()
                .bodyValue(requestBody)
                .retrieve()
                .bodyToMono(String.class)
                .timeout(Duration.ofMinutes(5)) // 设置超时时间为5分钟，确保10分钟内能完成
                .block();
            
            System.out.println("千问API响应: " + responseJson);
            
            if (responseJson != null) {
                try {
                    JsonNode rootNode = objectMapper.readTree(responseJson);
                    if (rootNode.has("output") && rootNode.path("output").has("text")) {
                        content = rootNode.path("output").path("text").asText();
                    } else {
                        // 将错误信息改为直接返回API响应内容，而不是错误消息
                        content = responseJson;
                    }
                } catch (Exception e) {
                    content = "解析API响应时出错: " + e.getMessage();
                }
            } else {
                content = "API响应为空";
            }
        } catch (Exception e) {
            e.printStackTrace();  // 打印完整堆栈跟踪
            content = "生成教学计划失败: " + (e.getMessage() != null ? e.getMessage() : "未知错误");
        }
        
        TeachingPlan plan = new TeachingPlan();
        plan.setSubject(subject);
        plan.setGrade(grade);
        plan.setTitle(topic);
        plan.setContent(content);
        plan.setDuration(45); // 默认45分钟
        
        return plan;
    }
    
    /**
     * 生成练习题
     */
    public String generateExercises(String stage, String subject, String grade, Integer questionCount, 
            List<String> questionTypes, String knowledgePoint, String difficultyLevel) {
        int maxRetries = 3;
        int retryCount = 0;
        Exception lastException = null;
        
        while (retryCount < maxRetries) {
            try {
                // 如果是重试，记录日志
                if (retryCount > 0) {
                    System.out.println("正在进行第" + retryCount + "次重试...");
                }
                
                // 构建提示词
                String prompt = String.format(
                    "请根据以下要求生成%d道%s学科的%s习题：\n" +
                    "1. 学习阶段：%s\n" +
                    "2. 年级：%s\n" +
                    "3. 题目类型：%s\n" +
                    "4. 知识点：%s\n" +
                    "5. 难度等级：%s\n" +
                    "6. 每道题需要包含：题目内容、答案和解析\n" +
                    "请以JSON数组格式返回，每个题目包含以下字段：\n" +
                    "- type: 题型(multiple-choice/fill-blank/short-answer)\n" +
                    "- content: 题目内容\n" +
                    "- options: 选项(选择题适用)\n" +
                    "- answer: 答案\n" +
                    "- explanation: 解析\n" +
                    "- difficulty: 难度\n\n" +
                    "特别注意：\n" +
                    "1. 解析中请使用纯文本表达数学公式，避免使用LaTeX格式如\\(E=mc^2\\)，应直接写成E=mc^2\n" +
                    "2. 避免使用转义字符\\后跟随特殊字符，如\\f, \\p等\n" +
                    "3. 返回的JSON必须是有效的、可直接解析的格式\n\n" +
                    "示例JSON格式：\n" +
                    "[{\"type\": \"multiple-choice\", \"content\": \"1+1=?\", " +
                    "\"options\": {\"A\": \"1\", \"B\": \"2\", \"C\": \"3\", \"D\": \"4\"}, " +
                    "\"answer\": \"B\", \"explanation\": \"1加1等于2\", \"difficulty\": \"简单\"}]",
                    questionCount,
                    subject,
                    String.join("、", questionTypes),
                    stage,
                    grade,
                    String.join("、", questionTypes),
                    knowledgePoint,
                    difficultyLevel
                );
                
                // 创建输入对象 - 直接使用prompt而非messages
                Map<String, Object> input = new HashMap<>();
                input.put("prompt", prompt);
                
                // 创建参数对象
                Map<String, Object> parameters = new HashMap<>();
                parameters.put("temperature", 0.7);
                parameters.put("max_tokens", 4000);
                parameters.put("result_format", "json"); // 要求返回JSON格式
                
                // 创建请求体
                Map<String, Object> requestBody = new HashMap<>();
                requestBody.put("model", model);  // 使用配置的模型名称
                requestBody.put("input", input);
                requestBody.put("parameters", parameters);
                
                System.out.println("发送请求到千问API: " + objectMapper.writeValueAsString(requestBody));
                
                String responseJson = qwenWebClient.post()
                    .bodyValue(requestBody)
                    .retrieve()
                    .bodyToMono(String.class)
                    .timeout(Duration.ofSeconds(120)) // 设置超时2分钟
                    .block();
                
                System.out.println("千问API响应: " + responseJson);

                // 解析响应
                if (responseJson != null) {
                    try {
                        JsonNode rootNode = objectMapper.readTree(responseJson);
                        String responseText = "";
                        
                        if (rootNode.has("output") && rootNode.path("output").has("text")) {
                            responseText = rootNode.path("output").path("text").asText();
                            
                            // 处理可能的Markdown代码块格式
                            if (responseText.trim().startsWith("```") || responseText.contains("```json")) {
                                // 移除起始的```json或```及结尾的```
                                responseText = responseText.replaceAll("```json\\s*", "")
                                                        .replaceAll("```\\s*$", "")
                                                        .replaceAll("^```\\s*", "");
                                System.out.println("处理后的JSON文本: " + responseText);
                            }
                            
                            // 处理LaTeX数学公式中的特殊字符转义，这些在JSON中是非法的
                            responseText = responseText.replaceAll("\\\\\\(", "\\\\\\\\(")  // 替换\(为\\(
                                                    .replaceAll("\\\\\\)", "\\\\\\\\)")      // 替换\)为\\)
                                                    .replaceAll("\\\\frac", "\\\\\\\\frac")  // 替换\frac为\\frac
                                                    .replaceAll("\\\\sum", "\\\\\\\\sum")    // 替换\sum为\\sum
                                                    .replaceAll("\\\\int", "\\\\\\\\int")    // 替换\int为\\int
                                                    .replaceAll("\\\\alpha", "\\\\\\\\alpha")// 替换\alpha为\\alpha
                                                    .replaceAll("\\\\beta", "\\\\\\\\beta")  // 替换\beta为\\beta
                                                    .replaceAll("\\\\gamma", "\\\\\\\\gamma")// 替换\gamma为\\gamma
                                                    .replaceAll("\\\\delta", "\\\\\\\\delta")// 替换\delta为\\delta
                                                    .replaceAll("\\\\theta", "\\\\\\\\theta")// 替换\theta为\\theta
                                                    .replaceAll("\\\\phi", "\\\\\\\\phi")    // 替换\phi为\\phi
                                                    .replaceAll("\\\\lambda", "\\\\\\\\lambda")// 替换\lambda为\\lambda
                                                    .replaceAll("\\\\pi", "\\\\\\\\pi")      // 替换\pi为\\pi
                                                    .replaceAll("\\\\nabla", "\\\\\\\\nabla")// 替换\nabla为\\nabla
                                                    .replaceAll("\\\\partial", "\\\\\\\\partial"); // 替换\partial为\\partial
                            
                            System.out.println("处理LaTeX特殊字符后的JSON文本: " + responseText.substring(0, Math.min(100, responseText.length())) + "...");
                            
                            // 尝试将返回的内容解析为习题并保存到数据库
                            try {
                                // 获取当前登录教师ID
                                String teacherId = TeacherContext.getTeacherId();
                                System.out.println("当前登录教师ID: " + teacherId);
                                
                                // 使用更安全的JSON解析方法
                                JsonNode exercisesNode = safelyParseJson(responseText);
                                if (exercisesNode != null && exercisesNode.isArray()) {
                                    List<Exercise> exercises = new ArrayList<>();
                                    
                                    for (JsonNode node : exercisesNode) {
                                        Exercise exercise = Exercise.builder()
                                            .subject(subject)
                                            .grade(grade)
                                            .topic(knowledgePoint)
                                            .questionType(node.path("type").asText())
                                            .content(node.path("content").asText())
                                            .answer(node.path("answer").asText())
                                            .analysis(node.path("explanation").asText())
                                            .difficulty(node.path("difficulty").asText())
                                            .teacherId(teacherId)
                                            .createdTime(LocalDateTime.now())
                                            .build();
                                        
                                        exercises.add(exercise);
                                    }
                                    
                                    // 保存到数据库
                                    for (Exercise exercise : exercises) {
                                        exerciseService.saveExercise(exercise);
                                    }
                                    
                                    System.out.println("成功保存" + exercises.size() + "道习题到数据库");
                                } else {
                                    // 如果不是JSON数组，尝试进行文本解析
                                    saveExercisesFromText(responseText, subject, grade, knowledgePoint, difficultyLevel, teacherId);
                                }
                            } catch (Exception e) {
                                System.out.println("保存习题到数据库时出错: " + e.getMessage());
                                e.printStackTrace();
                                // 即使保存失败，仍然返回原始响应
                            }
                            
                            return responseText;
                        } else {
                            // 返回原始响应内容
                            return responseJson;
                        }
                    } catch (Exception e) {
                        System.out.println("解析API响应时出错: " + e.getMessage());
                        return "{\"error\": \"解析API响应时出错: " + e.getMessage() + "\"}";
                    }
                } else {
                    System.out.println("API响应为空");
                    return "{\"error\": \"API响应为空\"}";
                }
            } catch (Exception e) {
                lastException = e;
                System.out.println("生成练习题失败，尝试重试 (" + (retryCount + 1) + "/" + maxRetries + "): " + e.getMessage());
                e.printStackTrace();
                retryCount++;
                
                // 等待一段时间再重试
                try {
                    Thread.sleep(2000 * retryCount); // 递增等待时间
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                }
            }
        }
        
        // 所有重试都失败
        return "{\"error\": \"生成习题失败，已重试" + maxRetries + "次: " + 
            (lastException != null ? lastException.getMessage() : "未知错误") + "\"}";
    }
    
    /**
     * 从文本格式解析习题并保存到数据库
     */
    private void saveExercisesFromText(String text, String subject, String grade, String topic, 
                                      String difficulty, String teacherId) {
        // 使用正则表达式提取习题
        Pattern exercisePattern = Pattern.compile(
            "【(\\S+)】问题\\d+：(.+?)\\n(?:(?:[A-D]：.+?\\n)+)?答案：(.+?)\\n解析：(.+?)(?:\\n---|$)", 
            Pattern.DOTALL);
        
        Matcher matcher = exercisePattern.matcher(text);
        int count = 0;
        
        while (matcher.find()) {
            String type = matcher.group(1);
            String content = matcher.group(2).trim();
            String answer = matcher.group(3).trim();
            String analysis = matcher.group(4).trim();
            
            // 将中文题型转换为英文
            String questionType;
            if (type.contains("选择题")) {
                questionType = "multiple-choice";
                
                // 提取选项
                Pattern optionPattern = Pattern.compile("([A-D])：(.*?)(?=\\n[A-D]：|\\n答案：)", Pattern.DOTALL);
                Matcher optionMatcher = optionPattern.matcher(matcher.group(0));
                
                StringBuilder contentWithOptions = new StringBuilder(content);
                contentWithOptions.append("\n");
                
                while (optionMatcher.find()) {
                    contentWithOptions.append(optionMatcher.group(1))
                        .append(". ")
                        .append(optionMatcher.group(2).trim())
                        .append("\n");
                }
                
                content = contentWithOptions.toString();
            } else if (type.contains("填空题")) {
                questionType = "fill-blank";
            } else if (type.contains("判断题")) {
                questionType = "true-false";
            } else {
                questionType = "short-answer";
            }
            
            Exercise exercise = Exercise.builder()
                .subject(subject)
                .grade(grade)
                .topic(topic)
                .questionType(questionType)
                .content(content)
                .answer(answer)
                .analysis(analysis)
                .difficulty(difficulty)
                .teacherId(teacherId)
                .createdTime(LocalDateTime.now())
                .build();
                
            exerciseService.saveExercise(exercise);
            count++;
        }
        
        System.out.println("从文本中解析并保存了" + count + "道习题到数据库");
    }
    
    public String analyzeStudentLevel(String studentId, String subject) {
        try {
            String prompt = String.format(
                "请分析学生%s在%s科目的学习水平，包括知识掌握度、学习积极性、应用能力以及针对性建议。",
                studentId, subject);
            
            // 创建输入对象 - 直接使用prompt而非messages
            Map<String, Object> input = new HashMap<>();
            input.put("prompt", prompt);
            
            // 创建参数对象
            Map<String, Object> parameters = new HashMap<>();
            parameters.put("temperature", 0.7);
            
            // 创建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", model);  // 使用配置的模型名称
            requestBody.put("input", input);
            requestBody.put("parameters", parameters);
            
            System.out.println("发送学生水平分析请求到千问API: " + objectMapper.writeValueAsString(requestBody));
            
            String responseJson = qwenWebClient.post()
                .bodyValue(requestBody)
                .retrieve()
                .bodyToMono(String.class)
                .block();
            
            System.out.println("学生水平分析响应: " + responseJson);
            
            if (responseJson != null) {
                try {
                    JsonNode rootNode = objectMapper.readTree(responseJson);
                    if (rootNode.has("output") && rootNode.path("output").has("text")) {
                        return rootNode.path("output").path("text").asText();
                    } else {
                        // 直接返回API的原始响应文本
                        JsonNode outputNode = rootNode.path("output");
                        return outputNode.toString();
                    }
                } catch (Exception e) {
                    return "解析API响应时出错: " + e.getMessage();
                }
            } else {
                return "API响应为空";
            }
        } catch (Exception e) {
            e.printStackTrace();  // 打印完整堆栈跟踪
            return "分析学生水平失败: " + (e.getMessage() != null ? e.getMessage() : "未知错误");
        }
    }

    /**
     * 生成学生能力评估
     * 
     * @param studentId 学生ID
     * @param subject 学科
     * @return 能力评估数据，包含各维度分数和评价内容
     */
    @SuppressWarnings("unchecked")
    public Map<String, Object> generateAbilityAssessment(String studentId, String subject) {
        try {
            String prompt = String.format(
                "请对学生ID为%s的%s学科能力进行详细评估，评估维度包括：\n" +
                "1. 知识维度：对基础概念和理论的理解程度\n" +
                "2. 应用维度：将知识应用到实际问题的能力\n" +
                "3. 创新维度：创新思维和解决问题的独特性\n\n" +
                "请给出以下评估内容：\n" +
                "1. 各维度的评分（满分10分）\n" +
                "2. 详细评估分析\n" +
                "3. 针对性改进建议\n\n" +
                "请按照以下JSON格式返回结果：\n" +
                "{\n" +
                "  \"knowledge_dimension\": 评分（浮点数，0-10）,\n" +
                "  \"application_dimension\": 评分（浮点数，0-10）,\n" +
                "  \"innovation_dimension\": 评分（浮点数，0-10）,\n" +
                "  \"assessment_details\": \"详细评估分析内容\",\n" +
                "  \"recommendation\": \"针对性改进建议\"\n" +
                "}",
                studentId, subject);
            
            // 创建输入对象
            Map<String, Object> input = new HashMap<>();
            input.put("prompt", prompt);
            
            // 创建参数对象
            Map<String, Object> parameters = new HashMap<>();
            parameters.put("temperature", 0.7);
            
            // 创建响应格式对象
            Map<String, String> responseFormat = new HashMap<>();
            responseFormat.put("type", "json_object");
            parameters.put("response_format", responseFormat);
            
            // 创建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", model);
            requestBody.put("input", input);
            requestBody.put("parameters", parameters);
            
            System.out.println("发送能力评估请求到千问API: " + objectMapper.writeValueAsString(requestBody));
            
            String responseJson = qwenWebClient.post()
                .bodyValue(requestBody)
                .retrieve()
                .bodyToMono(String.class)
                .timeout(Duration.ofSeconds(60))
                .block();
            
            System.out.println("千问API能力评估响应: " + responseJson);
            
            if (responseJson != null) {
                try {
                    JsonNode rootNode = objectMapper.readTree(responseJson);
                    if (rootNode.has("output") && rootNode.path("output").has("text")) {
                        String jsonText = rootNode.path("output").path("text").asText();
                        // 将JSON字符串转换为Map
                        return objectMapper.readValue(jsonText, Map.class);
                    } else {
                        // 处理非预期的响应格式
                        Map<String, Object> errorMap = new HashMap<>();
                        errorMap.put("knowledge_dimension", 5.0f);
                        errorMap.put("application_dimension", 5.0f);
                        errorMap.put("innovation_dimension", 5.0f);
                        errorMap.put("assessment_details", "AI评估生成失败，返回了非预期格式。原始响应: " + responseJson);
                        errorMap.put("recommendation", "请联系管理员检查AI服务状态。");
                        return errorMap;
                    }
                } catch (Exception e) {
                    // 解析失败，返回错误信息
                    Map<String, Object> errorMap = new HashMap<>();
                    errorMap.put("knowledge_dimension", 5.0f);
                    errorMap.put("application_dimension", 5.0f);
                    errorMap.put("innovation_dimension", 5.0f);
                    errorMap.put("assessment_details", "解析AI评估结果时出错: " + e.getMessage());
                    errorMap.put("recommendation", "请稍后重试或联系管理员。");
                    return errorMap;
                }
            } else {
                // 响应为空，返回错误信息
                Map<String, Object> errorMap = new HashMap<>();
                errorMap.put("knowledge_dimension", 5.0f);
                errorMap.put("application_dimension", 5.0f);
                errorMap.put("innovation_dimension", 5.0f);
                errorMap.put("assessment_details", "AI评估服务返回空响应");
                errorMap.put("recommendation", "请稍后重试或检查网络连接。");
                return errorMap;
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 发生异常，返回错误信息
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("knowledge_dimension", 5.0f);
            errorMap.put("application_dimension", 5.0f);
            errorMap.put("innovation_dimension", 5.0f);
            errorMap.put("assessment_details", "生成能力评估时发生错误: " + e.getMessage());
            errorMap.put("recommendation", "请联系系统管理员。");
            return errorMap;
        }
    }

    /**
     * 获取教师的教学计划历史记录
     * 
     * @param teacherId 教师ID
     * @return 该教师的教学计划列表
     */
    public List<TeachingPlan> getTeachingPlanHistory(String teacherId) {
        return teachingPlanService.findByTeacherId(teacherId);
    }
    
    /**
     * 获取TeachingPlanService实例，用于直接操作教学计划
     * 
     * @return TeachingPlanService实例
     */
    public TeachingPlanService getTeachingPlanService() {
        return teachingPlanService;
    }
    
    /**
     * 基于学生考试数据生成班级学情分析
     */
    public String generateClassAnalysis(String grade, String className, String subject, String testData) {
        try {
            // 构建提示词
            String prompt = String.format(
                "请根据以下%s年级%s班的%s科目考试数据进行学情分析：\n\n" +
                "%s\n\n" +
                "请提供以下分析内容：\n" +
                "1. 班级整体学习情况分析\n" +
                "2. 知识点掌握情况分析\n" +
                "3. 典型错误及原因分析\n" +
                "4. 学生分层（优秀/良好/中等/需提升）及特点\n" +
                "5. 教学改进建议\n" +
                "6. 个性化学习资源推荐\n\n" +
                "分析结果要求：\n" +
                "- 准确评估学生预备知识水平\n" +
                "- 针对不同层次学生提供差异化建议\n" +
                "- 提供具体可行的教学改进策略\n" +
                "- 推荐有针对性的学习资源",
                grade, className, subject, testData);
            
            // 创建输入对象
            Map<String, Object> input = new HashMap<>();
            input.put("prompt", prompt);
            
            // 创建参数对象
            Map<String, Object> parameters = new HashMap<>();
            parameters.put("temperature", 0.7);
            parameters.put("max_tokens", 4000);
            parameters.put("top_p", 0.8);
            parameters.put("result_format", "text");
            
            // 创建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", model);  // 使用配置的模型名称
            requestBody.put("input", input);
            requestBody.put("parameters", parameters);
            
            System.out.println("发送学情分析请求到千问API");
            
            String responseJson = qwenWebClient.post()
                .bodyValue(requestBody)
                .retrieve()
                .bodyToMono(String.class)
                .timeout(Duration.ofMinutes(5)) // 设置超时时间为5分钟
                .block();
            
            if (responseJson != null) {
                try {
                    JsonNode rootNode = objectMapper.readTree(responseJson);
                    if (rootNode.has("output") && rootNode.path("output").has("text")) {
                        return rootNode.path("output").path("text").asText();
                    } else {
                        return "API响应格式不正确: " + responseJson;
                    }
                } catch (Exception e) {
                    return "解析API响应时出错: " + e.getMessage();
                }
            } else {
                return "API响应为空";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "生成学情分析失败: " + (e.getMessage() != null ? e.getMessage() : "未知错误");
        }
    }

    // 添加一个安全解析JSON的方法
    private JsonNode safelyParseJson(String jsonString) {
        try {
            // 创建一个更宽松的ObjectMapper配置
            ObjectMapper relaxedMapper = new ObjectMapper();
            relaxedMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
            relaxedMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
            relaxedMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
            relaxedMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            // 禁用转义字符验证
            relaxedMapper.configure(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, true);
            
            // 尝试解析JSON
            return relaxedMapper.readTree(jsonString);
        } catch (Exception e) {
            System.out.println("JSON解析失败，尝试更宽松的解析方式: " + e.getMessage());
            try {
                // 进一步处理转义字符
                String processed = jsonString
                    .replaceAll("\\\\([^\"\\\\nt/bfr])", "\\\\\\\\$1");
                return objectMapper.readTree(processed);
            } catch (Exception e2) {
                System.out.println("二次JSON解析也失败: " + e2.getMessage());
                // 如果解析失败，返回null
                return null;
            }
        }
    }
} 